# -*- encoding: utf-8 -*-

"""
封装连接数据库及redis数据库操作方法
"""

from sshtunnel import SSHTunnelForwarder
import redis
import time
from Common.log import MyLog


class Redis:
    """
    封装连接redis操作方法
    """
    def __init__(self):
        self.log = MyLog

    def connect_database(self, db_info):
        """
        封装连接redis数据库的方法，支持通过跳板机连接和直接连接
        """
        host = db_info['host']
        port = int(db_info['port'])
        password = db_info['password']
        stepping = db_info['isJump']

        # 判断是否需要登录跳板机
        if stepping == 'yes':
            server_host = db_info['jumpHost']
            server_port = int(db_info['jumpPort'])
            server_name = db_info['jumpName']
            ssh_key = 'Config/id_rsa'

            # 定义开始的时间
            start_time = time.time()
            server = SSHTunnelForwarder(
                # 跳板机ip与ssh登录端口号
                ssh_address_or_host=(server_host, server_port),
                # 跳板机登录账号
                ssh_username=server_name,
                # PC(客户端)的私钥路径
                ssh_pkey=ssh_key,
                # 远程redis服务器的绑定的IP和端口号
                remote_bind_address=(host, port)
            )
            try:
                server.start()
                port = server.local_bind_port
                host = 'localhost'
                # 定义结束时间
                stop_time = time.time()
                self.log.info(
                    '---------Operation to complete !  connect-JumpServer-time: ' + str(
                        round((stop_time - start_time), 3)) + ' S')
            except Exception as e:
                raise e

        # 定义开始的时间
        start_time1 = time.time()
        try:
            r = redis.Redis(host=host, port=port, password=password, decode_responses=True)
            # 定义结束时间
            stop_time1 = time.time()
            self.log.info(
                '---------Operation to complete !  connect-redis-time: ' + str(
                    round((stop_time1 - start_time1), 3)) + ' S')
            return r
        except Exception as e:
            raise e